//
//  BKThoiKhoaBieuViewController.m
//  I'm BKer
//
//  Created by Nguyen Van Hoa on 5/15/13.
//  Copyright (c) 2013 vanhoavn. All rights reserved.
//

#import "BKThoiKhoaBieuViewController.h"
#import "BKThoiKhoaBieuCell.h"

static UIColor* currColor;

@interface BKThoiKhoaBieuViewController ()

@end

@implementation BKThoiKhoaBieuViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.title = @"Thời khoá biểu";
        self.tabBarItem.image = [UIImage imageNamed:@"first"];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSArray* arr = [BKStudentManager danhSachTKB];
    NSMutableDictionary* mDataMu = [[NSMutableDictionary alloc] init];
    for(int i=1;i<=7;i++){
        [mDataMu setObject:[[NSMutableArray alloc] init] forKey:[NSString stringWithFormat:@"%d",i]];
    }
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
    for(NSDictionary* dict in arr){
        BOOL hasDay = NO;
        NSString* ngay1 = [dict objectForKey:@"thu1"];
        if([ngay1 length]==1){
            hasDay = YES;
            [[mDataMu objectForKey:ngay1] addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                [NSString stringWithFormat:@"Thứ %@",ngay1,nil],@"ngay",
                                [NSString stringWithFormat:@"%@",ngay1,nil],@"thu",
                                [dict objectForKey:@"ten"], @"monhoc",
                                [NSString stringWithFormat:@"%@ - %@",
                                 [dict objectForKey:@"maso"],
                                 [dict objectForKey:@"nhom"]],@"mamonnhom",
                                [NSString stringWithFormat:@"Tiết %@ @ %@",
                                 [dict objectForKey:@"tiet1"],
                                 [dict objectForKey:@"phong1"]
                                 ],@"thoigiandiadiem",
                                [NSString stringWithFormat:@"%@%@",
                                 [dict objectForKey:@"thu1"],
                                 [dict objectForKey:@"tiet1"]
                                 ], @"sort",
                                nil]];
        }
        NSString* ngay2 = [dict objectForKey:@"thu2"];
        if([ngay2 length]==1){
            hasDay = YES;
            [[mDataMu objectForKey:ngay2] addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                [NSString stringWithFormat:@"Thứ %@",ngay2,nil],@"ngay",
                                [NSString stringWithFormat:@"%@",ngay2,nil],@"thu",
                                [dict objectForKey:@"ten"],@"monhoc",
                                [NSString stringWithFormat:@"%@ - %@",
                                 [dict objectForKey:@"maso"],
                                 [dict objectForKey:@"nhom"]],@"mamonnhom",
                                [NSString stringWithFormat:@"Tiết %@ - %@",
                                 [dict objectForKey:@"tiet2"],
                                 [dict objectForKey:@"phong2"]
                                 ],@"thoigiandiadiem",
                                [NSString stringWithFormat:@"%@%@",
                                 [dict objectForKey:@"thu2"],
                                 [dict objectForKey:@"tiet2"]
                                 ], @"sort",
                                nil]];
        }
        if(!hasDay){
            [[mDataMu objectForKey:@"1"] addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                @"--",@"ngay",
                                @"9",@"thu",
                                [dict objectForKey:@"ten"],@"monhoc",
                                [NSString stringWithFormat:@"%@ - %@",
                                 [dict objectForKey:@"maso"],
                                 [dict objectForKey:@"nhom"]],@"mamonnhom",
                                @"Môn không xếp thời khoá biểu",@"thoigiandiadiem",
                                @"000-00", @"sort",
                                nil]];
        }
    }
    NSMutableDictionary* mDataMu2 = [[NSMutableDictionary alloc] init];
    for(NSString* key in mDataMu){
        [mDataMu2 setObject:
         [[mDataMu objectForKey:key] sortedArrayWithOptions:NSSortStable
                                            usingComparator:^NSComparisonResult(NSDictionary* d1, NSDictionary* d2){
                                                return [[d1 objectForKey:@"sort"] compare:[d2 objectForKey:@"sort"]];
                                            }
                    ] forKey:key];
    }
    mData = [NSDictionary dictionaryWithDictionary:mDataMu2];
    
    currColor = [UIColor greenColor];
    currColor = [currColor colorWithAlphaComponent:0.3];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 7;
}
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(section==0) return @"Không xếp TKB";
    else if(section>0 && section<7) return [NSString stringWithFormat:@"Thứ %d",section+1,nil];
    return @"";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section>=0 && section<7) return [[mData objectForKey:[NSString stringWithFormat:@"%d",section+1]] count];
    return 0;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary* dict = [[mData objectForKey:[NSString stringWithFormat:@"%d",indexPath.section+1]] objectAtIndex:indexPath.row];
    if(dict!=NULL){
        NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
        NSInteger weekday = [weekdayComponents weekday];
        if(weekday==[[dict objectForKey:@"thu"] integerValue])
            cell.backgroundColor=currColor;
        else cell.backgroundColor=[UIColor whiteColor];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"BKThoiKhoaBieuCell";
    BKThoiKhoaBieuCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:nil options: nil] objectAtIndex:0];
    }
    NSDictionary* dict = [[mData objectForKey:[NSString stringWithFormat:@"%d",indexPath.section+1]] objectAtIndex:indexPath.row];
    if(dict!=NULL){
        cell.lblNgay.text = [dict objectForKey:@"ngay"];
        cell.lblMaMonNhom.text = [dict objectForKey:@"mamonnhom"];
        cell.lblMonhoc.text = [dict objectForKey:@"monhoc"];
        cell.lblThoigianDiadiem.text = [dict objectForKey:@"thoigiandiadiem"];
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section>=0 && indexPath.section<7) return 55;
    return 0;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}

@end
